package com.xk._02算法篇._11sequence;

/**
 * @description: 蛮力算法1 -- 优化
 * @author: xu
 * @date: 2022/10/23 22:02
 */
public class BruteForce02 {
    // 时间：O(n * m)
    // 空间：O(n + m)
    public static int indexOf(String test, String pattern) {
        if (test == null || pattern == null) return -1;
        char[] testChars = test.toCharArray();
        char[] patternChars = pattern.toCharArray();
        int tlen = testChars.length, plen = patternChars.length;
        if (tlen == 0 || plen == 0 || tlen < plen) return -1;

        int pi = 0, ti = 0, lenDelta = tlen - plen;
        while (pi < plen && (ti - pi) <= lenDelta) {
            if (testChars[ti] == patternChars[pi]) {
                pi++;
                ti++;
            } else {
                ti = ti - pi + 1;
                pi = 0;
            }
        }
        return pi == plen ? (ti - pi) : -1;
    }
}
